package com.kingzoon.seckill.service.impl.base;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kingzoon.seckill.dao.Oauth2ClientMapper;
import com.kingzoon.seckill.entity.Oauth2Client;
import com.kingzoon.seckill.entity.Oauth2ClientExample;
import com.kingzoon.seckill.service.ClientService;

import java.util.List;
import java.util.UUID;

@Transactional
@Service
public class ClientServiceImpl implements ClientService {
	@Autowired
	private Oauth2ClientMapper clientDao;

	private Oauth2ClientExample oauth2ClientExample = new Oauth2ClientExample();

	public Oauth2Client createClient(Oauth2Client client) {

		client.setClientId(UUID.randomUUID().toString());
		client.setClientSecret(UUID.randomUUID().toString());
		int a = clientDao.insertSelective(client);
		if (a != 1) {
			return null;
		}
		oauth2ClientExample.createCriteria().andClientIdEqualTo(client.getClientId());
		List<Oauth2Client> list = clientDao.selectByExample(oauth2ClientExample);
		if (list == null || list.size() <= 0) {
			return null;
		}
		client = list.get(0);
		return client;
	}

	public Oauth2Client updateClient(Oauth2Client client) {
		int a = clientDao.updateByPrimaryKeySelective(client);
		if (a != 1) {
			return null;
		}

		oauth2ClientExample.createCriteria().andClientIdEqualTo(client.getClientId());
		List<Oauth2Client> list = clientDao.selectByExample(oauth2ClientExample);
		if (list == null || list.size() <= 0) {
			return null;
		}
		client = list.get(0);
		return client;
	}

	public void deleteClient(Long clientId) {
		clientDao.deleteByPrimaryKey(clientId);
	}

	public Oauth2Client findOne(Long clientId) {
		return clientDao.selectByPrimaryKey(clientId);
	}

	public List<Oauth2Client> findAll() {
		return clientDao.selectByExample(oauth2ClientExample);
	}

	public Oauth2Client findByClientId(String clientId) {
		oauth2ClientExample.createCriteria().andClientIdEqualTo(clientId);
		List<Oauth2Client> list = clientDao.selectByExample(oauth2ClientExample);
		Oauth2Client oauth2Client = list.get(0);
		return oauth2Client;
	}

	public Oauth2Client findByClientSecret(String clientSecret) {
		oauth2ClientExample.createCriteria().andClientSecretEqualTo(clientSecret);
		List<Oauth2Client> list = clientDao.selectByExample(oauth2ClientExample);
		Oauth2Client oauth2Client = list.get(0);
		return oauth2Client;
	}
}
